package cn.work100.modular.msn.webSocket;

import cn.work100.core.common.constant.cache.Cache;
import cn.work100.core.util.CacheUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/webSocket")
@Component
public class WebSocket {
    //用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        Object wsonline1 = CacheUtil.get(Cache.CONSTANT, "wsonline");
        if (wsonline1 == null )
            CacheUtil.put(Cache.CONSTANT,"wsonline",1);
        if (wsonline1 != null )
            CacheUtil.put(Cache.CONSTANT,"wsonline",(int)wsonline1+1);
        this.session.getAsyncRemote().sendText("服务器连接成功,当前在线人数："+CacheUtil.get(Cache.CONSTANT, "wsonline"));
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        Integer wsonline = CacheUtil.get(Cache.CONSTANT, "wsonline");
        CacheUtil.put(Cache.CONSTANT,"wsonline",wsonline-1);
        webSocketSet.remove(this);  //从set中删除
     }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(message);
            //群发消息
            broadcast("["+jsonObject.get("username")+" - "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +"]"+"说：<span style='color:#000000'>"+jsonObject.get("messages")+"</span>");
        } catch (Exception e){
            onClose();
            onOpen(session);
            broadcast("<a href = '#' style='color: red'>会话拦截，请勿传输编码字符，已重新建立连接</a>");
        }

    }

    /**
     * 发生错误时调用
     *
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 群发自定义消息
     * */
    public void broadcast(String message){
        for (WebSocket item : webSocketSet) {
            //同步异步说明参考：websocket getAsyncRemote()和getBasicRemote()区别
            //this.session.getBasicRemote().sendText(message);
            item.session.getAsyncRemote().sendText(message);//异步发送消息.
        }
    }
}
